package com.cys.markdown.doc.admin.controller.sys;

import com.cys.common.data.RespCodeEnum;
import com.cys.common.pojo.RespEntity;
import com.cys.common.util.base.StringUtil;
import com.cys.mid.core.system.data.IsEnabledEnum;
import com.cys.mid.core.system.interfaces.entity.ISysRight;
import com.cys.mid.core.system.interfaces.entity.ISysRole;
import com.cys.mid.core.system.interfaces.entity.ISysUser;
import com.cys.mid.core.system.interfaces.service.SysRightService;
import com.cys.mid.core.system.interfaces.service.SysRoleService;
import com.cys.mid.core.system.interfaces.service.SysUserService;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 角色Controller
 *
 * @author caiyushen
 */
@Controller
@RequestMapping("/admin/sys/role")
@Transactional(rollbackFor = Exception.class)
public class RoleController {

    private final static Logger logger = LoggerFactory.getLogger(RoleController.class);

    @Resource(name = "sysUserServiceImpl")
    private SysUserService sysUserService;

    @Resource(name = "sysRoleServiceImpl")
    private SysRoleService sysRoleService;

    @Resource(name = "sysRightServiceImpl")
    private SysRightService sysRightService;


    /**
     * 获取列表信息
     *
     * @param pageNo   当前页
     * @param pageSize 当前页面显示数据量
     * @param param    检索条件
     * @author caiyushen
     */
    @ResponseBody
    @RequestMapping(value = "/getList", method = RequestMethod.GET)
    public RespEntity getList(Integer pageNo, Integer pageSize, @RequestParam Map param) {
        logger.debug("method[getList] param: " + param.toString());
        List<ISysRole> dataList = sysRoleService.findList(param);
        return new RespEntity(RespCodeEnum.success, dataList);
    }

    /**
     * 新增Role
     *
     * @param param SysRole实体类数据集
     * @author caiyushen
     */
    @ResponseBody
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public RespEntity add(@RequestParam Map param) throws Exception {
        logger.debug("method[add] param: " + param.toString());
        sysRoleService.save(param);
        return new RespEntity(RespCodeEnum.success);
    }


    /**
     * 修改Role
     *
     * @param param SysRole实体类数据集
     * @author caiyushen
     */
    @ResponseBody
    @RequestMapping(value = "/update", method = RequestMethod.PUT)
    public RespEntity update(@RequestParam Map param) throws Exception {
        logger.debug("method[update] param: " + param.toString());
        sysRoleService.update(param);
        return new RespEntity(RespCodeEnum.success);
    }

    /**
     * 删除Role
     *
     * @param id role主键
     * @author caiyushen
     */
    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    public RespEntity delete(Long id) {
        logger.info("method[delete] id: " + id);
        //判断该角色是否存在用户关联
        List<ISysUser> midList = sysUserService.findListByRoleId(id);
        if (!CollectionUtils.isEmpty(midList)) {
            return new RespEntity(RespCodeEnum.error, "请先删除该角色下的用户关联！");
        }
        //根据角色id删除 与权限关系
        sysRoleService.deleteRightRelByRoleId(id);
        //根据角色id删除 与用户关系
        sysRoleService.deleteUserRelByRoleId(id);
        //逻辑删除角色id
        sysRoleService.logicDeleteById(id);
        return new RespEntity(RespCodeEnum.success);
    }


    /**
     * 获取权限树
     */
    @ResponseBody
    @RequestMapping(value = "/getPrivilegeTree", method = RequestMethod.GET)
    public RespEntity getPrivilegeTree() {
        List<ISysRight> treeList = sysRightService.findTreeList(IsEnabledEnum.enabled);
        return new RespEntity(RespCodeEnum.success, treeList);
    }

    /**
     * 权限分配
     *
     * @param roleId       角色id
     * @param privilegeStr 权限id组（使用英文逗号隔开）
     */
    @ResponseBody
    @RequestMapping(value = "/savePrivilegeRole", method = RequestMethod.POST)
    public RespEntity savePrivilegeRole(Long roleId, String privilegeStr) {
        logger.debug("method[savePrivilegeRole] roleId:" + roleId + " privilegeStr:" + privilegeStr);
        if (!StringUtil.checkObj(roleId)) {
            logger.warn("method[savePrivilegeRole] roleId is null.");
            return new RespEntity(RespCodeEnum.deficiency);
        }
        if (!StringUtil.checkObj(privilegeStr)) {
            logger.warn("method[savePrivilegeRole] privilegeStr is null.");
            return new RespEntity(RespCodeEnum.deficiency);
        }
        //java8新特性之逗号分隔字符串转List<Long>
        Set<Long> dataList = Arrays.asList(privilegeStr.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toSet());
        sysRoleService.saveRelateRight(roleId, dataList);
        return new RespEntity(RespCodeEnum.success);
    }

    /**
     * 根据角色id获取权限数据
     *
     * @param roleId 角色id
     */
    @ResponseBody
    @RequestMapping(value = "/getPrivilegeByRoleId", method = RequestMethod.GET)
    public RespEntity getPrivilegeByRoleId(@RequestParam Long roleId) {
        logger.debug("method[getPrivilegeByRoleId]  roleId:" + roleId);
        List<ISysRight> dataList = sysRightService.findListByRoleId(roleId);
        return new RespEntity(RespCodeEnum.success, dataList);
    }

    /**
     * 根据角色id获取权限树
     *
     * @param roleId 角色id
     */
    @ResponseBody
    @RequestMapping(value = "/getTreeListByRoleId", method = RequestMethod.GET)
    public RespEntity getTreeListByRoleId(@RequestParam Long roleId) {
        logger.debug("method[getTreeListByRoleId]  roleId:" + roleId);
        List<ISysRight> dataList = sysRightService.findTreeListByRoleId(roleId);
        return new RespEntity(RespCodeEnum.success, dataList);
    }

    /**
     * 根据角色id获取用户列表
     *
     * @param pageNo               当前页
     * @param pageSize             当前页显示的数据量
     * @param param-sysRoleId      角色主键
     * @param param-sysUserAccount 用户账号
     * @param param-sysUserName    用户名称
     */
    @ResponseBody
    @RequestMapping(value = "/getUserListByRoleId", method = RequestMethod.GET)
    public RespEntity getUserListByRoleId(Integer pageNo, Integer pageSize, @RequestParam Map param) {
        if (!StringUtil.checkObj(param.get("sysRoleId"))) {
            logger.warn("method[getUserListByRoleId] sysRoleId is null.");
            return new RespEntity(RespCodeEnum.deficiency);
        }
        logger.debug("method[getUserListByRoleId]  param:" + param.toString());
        PageInfo<ISysUser> pageInfo = sysUserService.findRelRolePageUserDept(pageNo, pageSize, param);
        return new RespEntity(RespCodeEnum.success, pageInfo);
    }

    /**
     * 根据检索条件获取用户分页列表
     *
     * @param pageNo               当前页
     * @param pageSize             当前页显示的数据量
     * @param param-sysUserAccount 用户账号
     * @param param-sysUserName    用户名称
     */
    @ResponseBody
    @RequestMapping(value = "/getUserList", method = RequestMethod.GET)
    public RespEntity getUserList(Integer pageNo, Integer pageSize, @RequestParam Map param) {
        logger.debug("method[getUserList]  param:" + param.toString());
        PageInfo<ISysUser> pageInfo = sysUserService.findPageUserDept(pageNo, pageSize, param);
        return new RespEntity(RespCodeEnum.success, pageInfo);
    }

    /**
     * 根据角色id添加用户
     *
     * @param roleId 角色主键
     * @param userId 用户主键
     */
    @ResponseBody
    @RequestMapping(value = "/saveUserRelRole", method = RequestMethod.POST)
    public RespEntity saveUserRelRole(Long roleId, Long userId) {
        logger.info("method[saveUserRelRole]  roleId:" + roleId + " userId:" + userId);
        if (!StringUtil.checkObj(userId)) {
            logger.warn("method[saveUserRelRole] userId is null.");
            return new RespEntity(RespCodeEnum.deficiency);
        }
        if (!StringUtil.checkObj(roleId)) {
            logger.warn("method[saveUserRelRole] roleId is null.");
            return new RespEntity(RespCodeEnum.deficiency);
        }
        sysRoleService.saveRelateUser(roleId, userId);
        return new RespEntity(RespCodeEnum.success);
    }


}  